import { defineStore } from "pinia";
import { ref } from "vue";
import {
  getVacationRules,
  addVacationRule,
  updateVacationRule,
  deleteVacationRule,
} from "@/api/vacation";
import type { VacationRule } from "@/api/types/vacation";
import { ElMessage } from "element-plus";

export const useVacationStore = defineStore("vacation", () => {
  const rulesList = ref<VacationRule[]>([]);
  const loading = ref(true);

  // 获取假期规则列表
  const fetchRulesList = async () => {
    loading.value = true;
    try {
      const { data } = await getVacationRules();
      

      data.info_list.forEach((item)=>{
        if (item.naturalDayLeave=="1") {
          item.naturalDayLeave ="ziran"
        }else{
           item.naturalDayLeave ="gongri"
        }
      });

      if (data?.info_list) {
        rulesList.value = data.info_list;
      } else {
        ElMessage.error("获取假期规则失败");
      }
    } catch (error) {
      console.error("获取假期规则失败:", error);
      ElMessage.error("获取假期规则失败");
    } finally {
      loading.value = false;
    }
  };

  // 添加假期规则
  const addRule = async (data: Partial<VacationRule>) => {
    try {
      const res = await addVacationRule(data);
      if (res?.code === "200") {
        ElMessage.success(res.msg || "添加成功");
        await fetchRulesList();
        return true;
      } else {
        ElMessage.error(res?.msg || "添加失败");
        return false;
      }
    } catch (error) {
      console.error("添加假期规则失败:", error);
      ElMessage.error("添加失败");
      return false;
    }
  };

  // 更新假期规则
  const updateRule = async (data: Partial<VacationRule>) => {
    try {
      const res = await updateVacationRule(data);
      if (res?.code === "200") {
        ElMessage.success(res.msg || "更新成功");
        await fetchRulesList();
        return true;
      } else {
        ElMessage.error(res?.msg || "更新失败");
        return false;
      }
    } catch (error) {
      console.error("更新假期规则失败:", error);
      ElMessage.error("更新失败");
      return false;
    }
  };

  // 删除假期规则
  const deleteRule = async (id: number) => {
    try {
      const res = await deleteVacationRule(id);

      if (res?.code === "200") {
        ElMessage.success(res.msg || "删除成功");
        await fetchRulesList();
        return true;
      } else {
        ElMessage.error(res?.msg || "删除失败");
        return false;
      }
    } catch (error) {
      console.error("删除假期规则失败:", error);
      ElMessage.error("删除失败");
      return false;
    }
  };

  return {
    rulesList,
    loading,
    fetchRulesList,
    addRule,
    updateRule,
    deleteRule,
  };
});
